package com.xy.netty.dome.start;

import com.xy.netty.dome.constant.CommonConstant;
import com.xy.netty.dome.handler.EchoServerDelimiterHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author niuniu
 */
@Slf4j
public class EchoDelimiterServer {

    private final int port;

    public EchoDelimiterServer(int port){
        this.port = port;
    }

    /**
     * 启动流程
     */
    public void run() throws InterruptedException {
        //配置服务端线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            /**
                             *          指定消息分隔符的解码器
                             *            maxLength：
                             *                 表示一行最大的长度，如果超过这个长度依然没有检测自定义分隔符，将会抛出TooLongFrameException
                             *             stripDelimiter：
                             *                 解码后的消息是否去除掉分隔符
                             *             failFast：
                             *                 如果为true，则超出maxLength后立即抛出TooLongFrameException，不进行继续解码
                             *                 如果为false，则等到完整的消息被解码后，再抛出TooLongFrameException异常
                             *             delimiters：
                             *                 分隔符，ByteBuf类型
                             */
                            //是一个分隔符解码器
                            ByteBuf delimiter = Unpooled.copiedBuffer(CommonConstant.NEWS_END_DELIMITER.getBytes());
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024*1024,true,true,delimiter));
                            ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                            ch.pipeline().addLast(new EchoServerDelimiterHandler());
                        }
                    });
            //绑定端口，同步等待成功
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            if(channelFuture.isSuccess()){
                log.info("服务端启动端口：{}",port);
            }
            //等待服务端监听端口关闭
            channelFuture.channel().closeFuture().sync();
        }finally {

            //优雅退出，释放线程池
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }



    }


    public static void main(String [] args) throws InterruptedException {
        int port = 8080;
        if(args.length > 0){
            port = Integer.parseInt(args[0]);
        }

        new EchoDelimiterServer(port).run();

    }

}
